<script setup lang="ts">
import { ResourceContentApi, ResourceContentVO } from '@/api/resource/content'
import { ResourceGroupApi, ResourceGroupTreeVO } from '@/api/resource/group'
import { ResourceType } from '@/types/resource'
import VideoPlayer from '@/components/DiyEditor/components/mobile/VideoPlayer/index.vue'

const message = useMessage()
const emit = defineEmits(['selected'])

const show = ref(false)
const loading = ref(false)

const treeList = ref<ResourceGroupTreeVO[]>([])
const contentList = ref<ResourceContentVO[]>([])

// TODO 很奇怪，这里又变成了非数组？
const selectIds = ref<number>()
const selectId = computed(() => {
  // return selectIds.value?.at(-1)
  return selectIds.value
})
const selectContent = computed(
  () => contentList.value!.filter((content) => content.groupId === selectId.value)!
)

const cascaderProps = {
  value: 'id',
  label: 'name',
  children: 'groupChild',
  checkStrictly: true,
  emitPath: false
}

/** 打开窗口 */
const open = () => {
  show.value = true

  if (!treeList.value?.length || !contentList.value?.length) {
    getList()
  }
}
defineExpose({ open })

/** 关闭 */
const close = () => {
  currentVideo.value = undefined
  showVideo.value = false
  show.value = false
}

/** 获取数据 */
const getList = async () => {
  loading.value = true

  treeList.value = await ResourceGroupApi.getResourceGroupContentTreeList(ResourceType.VIDEO)
  contentList.value = await ResourceContentApi.getResourceList(ResourceType.VIDEO)

  loading.value = false
}

/** 获取第一帧图片 */
const imgMap = reactive<Record<string, string>>({})
watch(selectId, async () => {
  loading.value = true
  await Promise.all(
    contentList.value.map(async (item) => {
      if (!imgMap[item.url]) {
        await getImg(item.url)
      }
    })
  )
  loading.value = false
})
const getImg = async (url: string) => {
  return new Promise<void>((resolve, reject) => {
    const video = document.createElement('video')
    video.crossOrigin = 'anonymous'
    video.src = url

    video.addEventListener('loadedmetadata', () => {
      video.currentTime = 0.5 // 增大时间确保跳转有效

      video.addEventListener('seeked', () => {
        const canvas = document.createElement('canvas')
        canvas.width = video.videoWidth
        canvas.height = video.videoHeight
        const ctx = canvas.getContext('2d')
        if (ctx) {
          ctx.drawImage(video, 0, 0)
          imgMap[url] = canvas.toDataURL('image/jpeg')
          resolve() // 完成 Promise
        }
      })
    })

    video.addEventListener('error', reject)
  })
}

/** 点击视频 */
// 当前视频
const currentVideo = ref<ResourceContentVO>()
const showVideo = ref(false)
const handleClick = (item: ResourceContentVO) => {
  currentVideo.value = item
}

// 选择视频
const handleSelect = async () => {
  try {
    await message.confirm('确定要选择该视频吗?', '选择视频', 'info')
    emit('selected', currentVideo.value)
    close()
  } catch {}
}
</script>

<template>
  <Dialog v-model="show" title="选择图片" width="75%" :destroy-on-close="false">
    <div v-loading="loading">
      <el-scrollbar max-height="600">
        <el-row :gutter="16">
          <el-col :span="20">
            <ContentWrap>
              <!--              <el-empty v-if="!selectIds?.length" description="暂无数据" />-->
              <el-empty v-if="!selectContent.length" description="暂无数据" />
              <el-row v-else :gutter="8">
                <el-col v-for="item in selectContent" :key="item.id" :span="8">
                  <el-card :body-style="{ padding: '4px' }" @click="handleClick(item)">
                    <el-image class="h-56 w-full" :src="imgMap[item.url]" fit="fill">
                      <template #placeholder>
                        <div class="h-full w-full flex justify-center items-center">
                          <el-icon><Loading /></el-icon>
                        </div>
                      </template>
                    </el-image>
                    <el-space class="p-2" direction="vertical" alignment="normal">
                      <el-text size="large">{{ item.name }}</el-text>
                      <el-text type="info">{{ item.remark }}</el-text>
                    </el-space>
                  </el-card>
                </el-col>
              </el-row>
            </ContentWrap>
          </el-col>
          <el-col :span="4">
            <el-button class="w-full mb-4" v-loading="loading" type="primary" @click="getList">
              刷新
            </el-button>
            <ContentWrap>
              <el-cascader
                class="w-full"
                v-model="selectIds"
                :options="treeList"
                :props="cascaderProps"
                placeholder="请选择分组"
                clearable
              />
            </ContentWrap>
            <ContentWrap v-if="currentVideo">
              <el-image
                class="h-48 w-full"
                ref="currentImgRef"
                :src="imgMap[currentVideo.url]"
                fit="fill"
              >
                <template #placeholder>
                  <div class="h-full w-full flex justify-center items-center">
                    <el-icon><Loading /></el-icon>
                  </div>
                </template>
              </el-image>
              <el-space class="p-2" direction="vertical" alignment="normal">
                <el-text size="large">{{ currentVideo.name }}</el-text>
                <el-text type="info">{{ currentVideo.remark }}</el-text>
              </el-space>
            </ContentWrap>
            <ContentWrap v-if="currentVideo">
              <el-button @click="showVideo = true">预览</el-button>
              <el-button type="primary" @click="handleSelect">选择</el-button>
            </ContentWrap>
          </el-col>
        </el-row>
      </el-scrollbar>
    </div>
  </Dialog>

  <Dialog v-model="showVideo" title="视频预览">
    <VideoPlayer
      :property="{
        videoUrl: currentVideo!.url,
        style: {}
      }"
    />
  </Dialog>
</template>

<style scoped lang="scss"></style>
